﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using WindowsFormsApp1;
using HtmlAgilityPack;


public class DownLoadFileBllcs
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="html">html</param>
    /// <param name="saveBaseDir">保存到的物理路径(文件夹)</param>
    /// <param name="htmlName">保存的html名称(默认为index.html)</param>
    public static string SyncHtmlByUrl(string html, string saveBaseDir, string htmlName = "index.html")
    {
        StringBuilder newHtml = new StringBuilder(html);

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);

        HtmlNodeCollection imgNodes = doc.DocumentNode.SelectNodes("//img");
        List<DownLoadFileBllcs.ATLRLAttachment> imgList = new List<DownLoadFileBllcs.ATLRLAttachment>();

        if (imgNodes != null)
        {

            if (!Directory.Exists(saveBaseDir))
            {
                Directory.CreateDirectory(saveBaseDir); //在根目录下建立文件夹
            }

            string src;
            string extensionName;//后缀名称
            ATLRLAttachment tempImg;
            for (int i = 0; i < imgNodes.Count; i++)
            {
                if (imgNodes[i].Attributes["src"] != null)
                {
                    src = imgNodes[i].Attributes["src"].Value.Split('?')[0];//去掉url后面随机数 ?id=123
                    extensionName = GetExtension(src);

                    //svg格式下载有问题，暂不支持svg下载
                    if (!string.IsNullOrEmpty(src) && extensionName.ToLower() != "svg")
                    {
                        tempImg = new ATLRLAttachment();
                        //tempImg.FileContent = UrlToImage(src);
                        tempImg.ExtensioName = extensionName.Length==0?"jpg": extensionName;
                        tempImg.src = src;
                        imgList.Add(tempImg);
                    }
                }
            }

            if (imgList.Count > 0)
            {
                //下载图片并替换图片链接
                foreach (var img in imgList)
                {
                    extensionName = Guid.NewGuid().ToString("N") + "."+ img.ExtensioName;
                    FileDownLoad(img.src, saveBaseDir + "\\images\\" + extensionName);
                    newHtml.Replace(img.src, "images/" + extensionName);
                }
            }
        }


        TxtHelper.WriteTxt(saveBaseDir + "\\" + htmlName, newHtml.ToString());

        return newHtml.ToString();
    }

    /// <summary>
    /// 只能下载完整路径的图片
    /// </summary>
    /// <param name="url"></param>
    /// <param name="savePath"></param>
    public static void FileDownLoad(string url, string savePath)
    {
        try
        {
            var fileName = Path.GetFileName(savePath);
            var divPath = savePath.Replace(fileName, string.Empty);
            if (!Directory.Exists(divPath))
            {
                Directory.CreateDirectory(divPath); //在根目录下建立文件夹
            }

            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream reader = response.GetResponseStream();
            FileStream writer = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
            byte[] buff = new byte[512];
            int c = 0; //实际读取的字节数
            while ((c = reader.Read(buff, 0, buff.Length)) > 0)
            {
                writer.Write(buff, 0, c);
            }
            writer.Close();
            writer.Dispose();
            reader.Close();
            reader.Dispose();
            response.Close();
        }
        catch (Exception ex)
        {
           
        }

    }

    public static void DeleteDir(string filePath)
    {
        try
        {
            //去除文件夹和子文件的只读属性
            //去除文件夹的只读属性
            System.IO.DirectoryInfo fileInfo = new DirectoryInfo(filePath);
            fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

            //去除文件的只读属性
            System.IO.File.SetAttributes(filePath, System.IO.FileAttributes.Normal);

            //判断文件夹是否还存在
            if (Directory.Exists(filePath))
            {
                foreach (string f in Directory.GetFileSystemEntries(filePath))
                {
                    if (File.Exists(f))
                    {
                        //如果有子文件删除文件
                        File.Delete(f);
                        Console.WriteLine(f);
                    }
                    else
                    {
                        //循环递归删除子文件夹
                        DeleteDir(f);
                    }
                }

                //删除空文件夹
                Directory.Delete(filePath);
                Console.WriteLine(filePath);
            }
        }
        catch (Exception ex) // 异常处理
        {
            Console.WriteLine(ex.Message.ToString());// 异常信息
        }
    }


    /// <summary>
    /// GET请求
    /// </summary>
    /// <returns></returns>
    public static string HttpGET(string GETURL)
    {
        HttpWebRequest request = null;
        HttpWebResponse response = null;
        try
        {
            request = System.Net.WebRequest.Create(GETURL) as HttpWebRequest;
            request.Method = "GET";
            response = request.GetResponse() as HttpWebResponse;
        }
        catch (WebException exception)
        {
            if (exception.Status == WebExceptionStatus.ProtocolError)
            {
                response = (HttpWebResponse)exception.Response;
            }
            if (exception.Status == WebExceptionStatus.ConnectFailure)
            {
                return exception.Message;
            }
        }
        catch (Exception)
        {
            if (response != null)
            {
                response.Close();
            }
            return string.Empty;
        }

        if (response != null)
        {
            Encoding enc = string.IsNullOrEmpty(response.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(response.CharacterSet);
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), enc))
            {
                string tempStr = sr.ReadToEnd();
                response.Close();
                return tempStr;
            }
        }
        return string.Empty;

        //------如果上面的方法不好用，请用下面的方法来请求------
        TcpClientHttpRequest hr = new TcpClientHttpRequest();
        hr.Action = GETURL;
        //hr.Method = "get"; //默认
        hr.Send();
        return hr.Response.Xml;
    }


    public static string GetExtension(string url)
    {
        url = url.Split('/').Last();
        if (url.Contains("."))
        {
            return url.Split('.').Last();
        }

        return string.Empty;
    }



    /// <summary>
    /// 定义一个图片的类
    /// </summary>
    public class ATLRLAttachment
    {
        /// <summary>
        /// 图片src
        /// </summary>
        public string src { get; set; }

        /// <summary>
        /// 图片后缀名称
        /// </summary>
        public string ExtensioName { get; set; }

    }



}
